package util;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.Cell;
import org.apache.hadoop.hbase.CellScanner;
import org.apache.hadoop.hbase.CellUtil;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.*;

import java.io.IOException;

public class HbaseUtil {
    private static Connection conn;

    static {
        try {
            // 1、获取配置对象
            Configuration conf = new Configuration();
            // 2、配置zookeeper的参数
            conf.set("hbase.zookeeper.quorum", "192.168.1.171:2181");
//            conf.set("hbase.zookeeper.quorum", "192.168.1.171");
//            conf.set("hbase.zookeeper.property.clientPort", "2181");
            // 3、获取连接对象
            conn = ConnectionFactory.createConnection(conf);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    /**
     * 获取DDL操作的客户端Admin
     */
    public static Admin getAdmin() {
        Admin admin = null;
        try {
            admin = conn.getAdmin();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return admin;
    }

    /**
     * 关闭客户端Admin
     */
    public static void closeAdmin(Admin admin) {
        try {
            if (admin != null) {
                admin.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    /*******************************table的CRUD(DML+DQL)*************************************/
    /**
     * 获取table对象的方法
     */
    public static Table getTable(String name) {
        Table table = null;

        try {
            //将表名转成TableName对象
            TableName tableName = TableName.valueOf(name);
            //通过连接对象。获取table对象
            table = conn.getTable(tableName);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return table;
    }


    /**
     * 关闭表对象
     */
    public static void closeTable(Table table) {
        try {
            if (table != null) {
                table.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }


    public static void printResult(Result rs) throws IOException {
        CellScanner sc = rs.cellScanner();
        while (sc.advance()) {
            Cell cell = sc.current();
            System.out.print(new String(CellUtil.cloneRow(cell)) + "\t");
            System.out.print(new String(CellUtil.cloneFamily(cell), "utf8") + "\t");
            System.out.print(new String(CellUtil.cloneQualifier(cell), "utf8") + "\t");
            System.out.println(new String(CellUtil.cloneValue(cell), "utf8") + "\t");
        }
    }

}